<template>
  <base-page v-bind="baseInfo">
    <template #searchBar>
      <filter-form
        v-if="show"
        ref="filterForm"
        :elements="elements"
        :hand="true"
        @submit="submit"
        @reset="reset"
      >
        <template>
          <el-button icon="el-icon-download" @click="downloadTemplateFun">导出</el-button>
        </template>
      </filter-form>
    </template>

    <template #content>
      <el-tabs v-model="activeName">
        <el-tab-pane label="业务职能" name="business" />
        <el-tab-pane label="管理职能" name="manage" />
      </el-tabs>

      <div class="table-box">
        <TableNew
          v-show="activeName === 'business'"
          :loading="tableLoading"
          :data="tableData"
          :columns="businessColumns"
          :pagination="pagination"
          :cell-style="cellStyle"
          @paginationChange="paginationChange"
        />

        <TableNew
          v-show="activeName === 'manage'"
          :loading="tableLoading"
          :data="tableData"
          :columns="manageColumns"
          :pagination="pagination"
          :cell-style="cellStyle"
          @paginationChange="paginationChange"
        />
      </div>
    </template>
  </base-page>
</template>

<script>

import listMixins from '@/mixins/budgetQuert/listMixins'
import exportDownload from '@/mixins/budgetQuert/exportDownload'
import {
  exportExcelYsManageAllResults,
  listYsBusinessAllResults,
  listYsDictionary, listYsManageAllResults
} from '@/api/budgetQuert'
import { getQuarter } from '@/utils/publicFun'
import { listYsDepartment } from '@/api/public'

export default {
  name: 'HospitalResult', // 部门预算执行结果
  mixins: [listMixins, exportDownload],
  data() {
    return {
      baseInfo: {
        searchBarShow: true
      },

      name: '全院预算执行结果-',
      exportName: '',
      reconstruction: true,

      filterFormShow: true,

      elements: [],
      elementsBusiness: [
        {
          label: '期间',
          type: 'date-picker',
          mode: 'monthrange',
          format: 'yyyy-MM',
          key: 'date',
          value: ''
        },
        {
          label: '预算科目名称',
          type: 'input',
          key: 'subjectName',
          width: 140,
          value: ''
        }
      ],
      elementsManage: [
        {
          label: '类别',
          type: 'select',
          options: [],
          hideSelectAll: true,
          key: 'subjectType',
          itemValue: 'id',
          itemLabel: 'dictionaryName',
          value: ''
        },
        {
          label: '部门',
          type: 'select',
          options: [],
          key: 'departmentCode',
          value: ''
        }
      ],

      activeName: '',
      businessColumns: [
        {
          title: '预算科目名称',
          dataIndex: 'subjectName',
          fixed: 'left',
          width: 100
        }
      ],
      manageColumns: [
        {
          title: '类别',
          dataIndex: 'category',
          fixed: 'left',
          width: 100
        },
        {
          title: '预算科目名称',
          dataIndex: 'subjectName',
          fixed: 'left',
          width: 100
        },
        {
          title: '责任部门',
          dataIndex: 'deptNames',
          fixed: 'left',
          width: 100
        },
        {
          title: '预算下达',
          type: 'hasMerge',
          mergeList: [
            {
              title: '三香(元)',
              dataIndex: 'xsan',
              format: true,
              align: 'right'
            },
            {
              title: '浒关(元)',
              dataIndex: 'xxu',
              format: true,
              align: 'right'
            },
            {
              title: '合计(元)',
              dataIndex: 'xall',
              format: true,
              align: 'right'
            }
          ]
        },
        {
          title: '执行',
          type: 'hasMerge',
          mergeList: [
            {
              title: '三香(元)',
              dataIndex: 'zsan',
              format: true,
              align: 'right'
            },
            {
              title: '浒关(元)',
              dataIndex: 'zxu',
              format: true,
              align: 'right'
            },
            {
              title: '合计(元)',
              dataIndex: 'zall',
              format: true,
              align: 'right'
            }
          ]
        },
        {
          title: '执行率',
          type: 'hasMerge',
          mergeList: [
            {
              title: '三香(%)',
              dataIndex: 'sanM',
              format: true,
              align: 'right'
            },
            {
              title: '浒关(%)',
              dataIndex: 'xuM',
              format: true,
              align: 'right'
            },
            {
              title: '合计(%)',
              dataIndex: 'allM',
              format: true,
              align: 'right'
            }
          ]
        }
      ],
      tableData: [],
      show: true
    }
  },
  computed: {
    params() {
      return this.$refs.filterForm.getParms()
    }
  },
  watch: {
    activeName(val) {
      this.tableData = []
      this.show = false
      if (val === 'business') {
        this.elements = this.elementsBusiness
        this.listInterface = listYsBusinessAllResults
        this.downloadInterface = exportExcelYsManageAllResults
        this.exportName = '业务职能'
      } else {
        this.elements = [...this.elementsBusiness, ...this.elementsManage]
        this.listInterface = listYsManageAllResults
        this.downloadInterface = exportExcelYsManageAllResults
        this._listYsDepartment()
        this.exportName = '管理职能'
      }

      setTimeout(() => {
        this.show = true
        this.$refs.filterForm && this.$refs.filterForm.submitFormFilter()
      })
    }
  },
  mounted() {
    this.activeName = 'business'

    this.$nextTick(() => {
      const quarter = getQuarter('YYYY-MM')
      this.elements[0].value = [quarter.startTime, quarter.endTime]

      this.listYsDictionaryFun()
    })
  },
  methods: {
    async _listYsDepartment() {
      try {
        const { data } = await listYsDepartment({ status: 1 })
        if (data.code === 200) {
          this.elements.find(i => i.key === 'departmentCode').options.push(...data.data.map(j => ({ label: j.departmentName, value: j.departmentCode })))
        } else {
          this.$message.error(data.message || '部门获取失败')
        }
      } catch (error) {
        console.log(error)
      }
    },

    reset() {
      const quarter = getQuarter('YYYY-MM')
      const params = {
        date: [quarter.startTime, quarter.endTime],
        subjectName: ''
      }

      if (this.activeName !== 'business') {
        params.subjectType = ''
        params.departmentCode = ''
      }

      this.$refs.filterForm.handleForceSet(params)
      this.getData()
    },

    listYsDictionaryFun() {
      listYsDictionary({ selectType: 'subjectType' }).then(res => {
        if (res.code === 200) {
          this.elementsManage[0].options = res.data
        } else {
          this.$message.error('获取数据失败')
        }
      })
    },

    downloadTemplateFun() {
      const param = this.$refs.filterForm.getParms()

      if (param && param.date) {
        param.startTime = param.date[0]
        param.endTime = param.date[1]

        delete param.date
      }

      this.downloadTemplate(param, this.exportName)
    },

    dataReconstruction(res) {
      if (this.activeName === 'business') {
        this.businessColumns = [
          {
            title: '预算科目名称',
            dataIndex: 'subjectName',
            fixed: 'left',
            width: 100
          }
        ]

        if (res.data.listHead && res.data.listHead.length) {
          res.data.listHead.forEach((item, index) => {
            this.businessColumns.push({
              title: item.deptName,
              type: 'hasMerge',
              mergeList: [
                {
                  title: item.monthName,
                  dataIndex: String(2 * index),
                  format: true,
                  align: 'right'
                },
                {
                  title: item.yearName,
                  dataIndex: String(2 * index + 1),
                  format: true,
                  align: 'right'
                }
              ]
            })
          })
        }

        this.tableData = res.data.listData?.list?.length ? res.data.listData.list.map(i => {
          const temp = {}
          temp.subjectName = i.subjectName
          i.data.forEach((item, index) => {
            temp[index] = i.flag[index] ? '#' : item
          })
          return temp
        }) : []

        this.pagination.total = res.data.listData.total
      }

      if (this.activeName === 'manage') {
        const data = res.data.list
        for (let i = 0; i < data.length; i++) {
          for (const key in data[i]) {
            if (key + 'Flag' in data[i] && !!data[i][key + 'Flag']) {
              data[i][key] = '#'
            }
          }
        }

        this.tableData = data
        this.pagination.total = res.data.total
      }
    },

    cellStyle(row) {
      if (row.column.property in row.row && row.row[row.column.property] === '#') {
        return 'color: #FF0000'
      }
    }
  }
}
</script>

<style lang="less" scoped>
.table-box {
  height: 100%;
  display: flex;
  flex-direction: column;
}
</style>
